<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">






















<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="上一篇文章中主要讲述一个完整的HTTP请求过程，了解一个连接是如何建立的。那么，这里再来聊聊web 中常用的几种通信方式，主要讲述其概念和应用场景或实现方式。概况一下，主要有四种方式，它们分别是短轮询、长轮询(comet)、长连接(SSE)、WebSocket。它们大体可以分为两类，一种是在HTTP基础上实现的，包括短轮询、comet和SSE；另一种不是在HTTP基础上实现是，即WebSocke">
<meta name="keywords" content="web">
<meta property="og:type" content="article">
<meta property="og:title" content="web 的几种通信方式">
<meta property="og:url" content="https://qimajiang.com/2017/08/18/web 的几种通信方式/index.html">
<meta property="og:site_name" content="启码匠 - 磨刀霍霍向编程">
<meta property="og:description" content="上一篇文章中主要讲述一个完整的HTTP请求过程，了解一个连接是如何建立的。那么，这里再来聊聊web 中常用的几种通信方式，主要讲述其概念和应用场景或实现方式。概况一下，主要有四种方式，它们分别是短轮询、长轮询(comet)、长连接(SSE)、WebSocket。它们大体可以分为两类，一种是在HTTP基础上实现的，包括短轮询、comet和SSE；另一种不是在HTTP基础上实现是，即WebSocke">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-06-24T06:11:04.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="web 的几种通信方式">
<meta name="twitter:description" content="上一篇文章中主要讲述一个完整的HTTP请求过程，了解一个连接是如何建立的。那么，这里再来聊聊web 中常用的几种通信方式，主要讲述其概念和应用场景或实现方式。概况一下，主要有四种方式，它们分别是短轮询、长轮询(comet)、长连接(SSE)、WebSocket。它们大体可以分为两类，一种是在HTTP基础上实现的，包括短轮询、comet和SSE；另一种不是在HTTP基础上实现是，即WebSocke">





  
  
  <link rel="canonical" href="https://qimajiang.com/2017/08/18/web 的几种通信方式/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>web 的几种通信方式 | 启码匠 - 磨刀霍霍向编程</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">启码匠 - 磨刀霍霍向编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">磨刀霍霍向编程</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://qimajiang.com/2017/08/18/web 的几种通信方式/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="启码匠">
      <meta itemprop="description" content="学习如磨刀， 需要不断温故。">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="启码匠 - 磨刀霍霍向编程">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">web 的几种通信方式

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2017-08-18 01:11:07" itemprop="dateCreated datePublished" datetime="2017-08-18T01:11:07+08:00">2017-08-18</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-06-24 14:11:04" itemprop="dateModified" datetime="2019-06-24T14:11:04+08:00">2019-06-24</time>
              
            
          </span>

          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li><p>上一篇文章中主要讲述一个完整的HTTP请求过程，了解一个连接是如何建立的。那么，这里再来聊聊web 中常用的几种通信方式，<br>主要讲述其概念和应用场景或实现方式。概况一下，主要有四种方式，它们分别是短轮询、长轮询(comet)、长连接(SSE)、WebSocket。它们大体可以分为两类，一种是在HTTP基础上实现的，包括短轮询、comet和SSE；另一种不是在HTTP基础上实现是，即WebSocket。</p>
<a id="more"></a>

</li>
</ul>
<h3 id="Ajax-轮询"><a href="#Ajax-轮询" class="headerlink" title="Ajax 轮询"></a>Ajax 轮询</h3><h4 id="1、原理"><a href="#1、原理" class="headerlink" title="1、原理"></a>1、原理</h4><p>（1）、客户端向服务器端发起请求，和上面最基本的请求原理是一样<br>(2)、不同的是该请求方式是通过Ajax实现，设定一定的间隔时间对服务器发送请求(比如1 秒)，通过setInterval()方法，实现每隔一段时间向服务器发送请求的功能。<br>(3)、服务器端返回结果到客户端</p>
<h4 id="2、实现"><a href="#2、实现" class="headerlink" title="2、实现"></a>2、实现</h4><p>（1）、前端实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">&lt;meta charset=&quot;utf-8&quot;&gt;</span><br><span class="line">&lt;title&gt;短轮询ajax实现&lt;/title&gt;</span><br><span class="line">&lt;script type=&quot;text/javascript&quot; src=&quot;../jquery.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    </span><br><span class="line">        &lt;div id=&quot;msgs&quot;&gt;&lt;/div&gt;</span><br><span class="line"> </span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;script type=&quot;text/javascript&quot;&gt;</span><br><span class="line">    function showUnreadNews()&#123;</span><br><span class="line">            $(document).ready(function() &#123;</span><br><span class="line">//使用jquery的ajax方法</span><br><span class="line">                $.ajax(&#123;</span><br><span class="line">                  type: &quot;GET&quot;,</span><br><span class="line">                  url: “shortAjax.php&quot;,   </span><br><span class="line">                  dataType: &quot;json&quot;,</span><br><span class="line">        </span><br><span class="line">                  success: function(msg) &#123;</span><br><span class="line">                      $.each(msg, function(id, title) &#123;</span><br><span class="line">                          $(&quot;#msgs&quot;).append(&quot;&lt;a&gt;&quot; + title + &quot;&lt;/a&gt;&lt;br&gt;&quot;);</span><br><span class="line">                      &#125;);</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line"> </span><br><span class="line">        setInterval(&apos;showUnreadNews()&apos;,2000);//2秒请求一次</span><br><span class="line">&lt;/script&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<p>（2）后端实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">$arr = array(&apos;title&apos;=&gt;&apos;标题&apos;,&apos;text&apos;=&gt;&apos;内容&apos;);   //服务器端更新的数据</span><br><span class="line">echo json_encode($arr);  //返回数据</span><br><span class="line">?&gt;</span><br></pre></td></tr></table></figure>

<h4 id="3、应用"><a href="#3、应用" class="headerlink" title="3、应用"></a>3、应用</h4><p>这种方式由于需要不断的建立http连接，严重浪费了服务器端和客户端的资源。最初是用来实现实时更新数据的， 但服务器的压力和用户数成正比，最终会超过服务器的承受范围，造成严重后果。<br>因此短轮询不适用于那些同时在线用户数量比较大，并且很注重性能的Web应用。</p>
<h3 id="comet"><a href="#comet" class="headerlink" title="comet"></a>comet</h3><h4 id="1、原理-1"><a href="#1、原理-1" class="headerlink" title="1、原理"></a>1、原理</h4><p>comet与传统的ajax区别在于，客户端会与服务器端保持一个长连接，此时该连接先挂起，不做响应。只有当客户端需要的数据更新时，服务器才会主动将数据推送给客户端。comet的实现有两种方式，一种方式是使用基于ajax的长轮询，另一种方式是基于Iframe及htmlfile的流方式。基于ajax的长轮询方式中，服务器端在接受到客户端ajax发送的请求后，不立即返回响应，而是阻塞请求直到超时或有数据更新。当服务器端在上述情况下返回响应后，客户端通过js再次发送请求建立连接，重复上述步骤。</p>
<h4 id="2、实现-1"><a href="#2、实现-1" class="headerlink" title="2、实现"></a>2、实现</h4><p>前端实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">&lt;!doctype html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">&lt;meta charset=&quot;utf-8&quot;&gt;</span><br><span class="line">&lt;title&gt;长轮询ajax实现&lt;/title&gt;</span><br><span class="line">&lt;script type=&quot;text/javascript&quot; src=&quot;../jquery.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;input type=&quot;button&quot; id=&quot;btn&quot; value=&quot;click&quot;&gt;</span><br><span class="line">&lt;div id=&quot;msg&quot;&gt;数据情况&lt;/div&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;script type=&quot;text/javascript&quot;&gt;</span><br><span class="line">$(function()&#123;</span><br><span class="line">        $(&quot;#btn&quot;).bind(&apos;click&apos;,&#123;btn:$(&apos;#btn&apos;)&#125;,function(e)&#123;</span><br><span class="line">            $.ajax(&#123;</span><br><span class="line">                type: &apos;POST&apos;,</span><br><span class="line">                dataType: &apos;json&apos;,               </span><br><span class="line">                url: &apos;ajax.php&apos;,</span><br><span class="line">                timeout: &apos;20000&apos;,//设置请求超时时间</span><br><span class="line">                data: &#123;time: &apos;2000000&apos;&#125;,// 每次请求等待时间，将其传到后台用来挂起请求</span><br><span class="line">                success: function(data,status)&#123;</span><br><span class="line">//对返回的数据进行判断和读取</span><br><span class="line">                    if(data.success == &apos;1&apos;)&#123;</span><br><span class="line">                    $(&quot;#msg&quot;).append(&apos;&lt;br&gt;[有数据]&apos;+data.text);</span><br><span class="line">                    e.data.btn.click();  //再此发送请求</span><br><span class="line">                &#125;</span><br><span class="line">                    // 未从服务器中获的数据</span><br><span class="line">                      if(data.success == &apos;0&apos;)&#123;</span><br><span class="line">                        $(&quot;#msg&quot;).append(&apos;&lt;br&gt;[无数据]&apos;);</span><br><span class="line">                            e.data.btn.click();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;,</span><br><span class="line">                // ajax超时,继续查询</span><br><span class="line">                error:function(XMLHttpRequest,textStatus,errorThrown)&#123;</span><br><span class="line">                     if(textStatus == &quot;timeout&quot;)&#123;</span><br><span class="line">                        $(&quot;#msg&quot;).append(&apos;超时&apos;);</span><br><span class="line">                        e.data.btn.click();</span><br><span class="line">                     &#125;</span><br><span class="line">                &#125;</span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&lt;/script&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<p>后端 PHP 实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">  set_time_limit(0);// 无限请求超时时间</span><br><span class="line">  usleep($_POST[&apos;time’]);//通过前台传过来的数据设置挂起时间</span><br><span class="line">  while(true)&#123;   //无限循环</span><br><span class="line">      $rand = rand(1,999);</span><br><span class="line">      if($rand &lt; 500)&#123;</span><br><span class="line">          $arr = array(&apos;success&apos;=&gt;&apos;1&apos;,&apos;name&apos;=&gt;&apos;有值&apos;,&apos;text&apos;=&gt;$rand);</span><br><span class="line">          echo json_encode($arr);</span><br><span class="line">          exit();</span><br><span class="line">      &#125;else&#123;</span><br><span class="line">          $arr = array(&apos;success&apos;=&gt;&apos;0&apos;,&apos;name&apos;=&gt;&apos;无值&apos;,&apos;text&apos;=&gt;$rand);</span><br><span class="line">          echo json_encode($arr);</span><br><span class="line">          exit();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">?&gt;</span><br></pre></td></tr></table></figure>

<h4 id="3、应用-1"><a href="#3、应用-1" class="headerlink" title="3、应用"></a>3、应用</h4><p>长轮询和短轮询比起来，明显减少了很多不必要的http请求次数，相比之下节约了资源。长轮询的缺点在于，连接挂起也会导致资源的浪费。应用场景跟短轮询相差无几。</p>
<h3 id="SSE"><a href="#SSE" class="headerlink" title="SSE"></a>SSE</h3><h4 id="1、概述"><a href="#1、概述" class="headerlink" title="1、概述"></a>1、概述</h4><p>SSE是HTML5新增的功能，全称为Server-SentEvents。它可以允许服务推送数据到客户端。SSE在本质上就与之前的长轮询、短轮询不同，虽然都是基于http协议的，但是轮询需要客户端先发送请求。而SSE最大的特点就是不需要客户端发送请求，可以实现只要服务器端数据有更新，就可以马上发送到客户端。</p>
<h4 id="2、原理"><a href="#2、原理" class="headerlink" title="2、原理"></a>2、原理</h4><p>SSE不需要依赖客户端向服务器发送请求，而是可以直接在服务器端有数据更新时进行发送到客户端，相比于轮询的“拉数据”，这种“推数据” 有着低延迟、高性能的优势。</p>
<p>这种方法的服务器端非常简介，只要维护一个服务器和客户端之间的协议即可。前端使用EventSource对象。</p>
<p>服务器端需要提供的协议基本代码如下：</p>
<p>data:firstevent</p>
<p>data:secondevent</p>
<p>id:100</p>
<p>event:myevent</p>
<p>data:thirdevent</p>
<p>id:101</p>
<p>:thisisacomment</p>
<p>data:fourthevent</p>
<p>data:fourtheventcontinue</p>
<p>下面解释一下基本用法。要定义各个事件，每一个事件之间使用一个换行符隔开。每个事件内部可以有多行，每一行都是type:value的形式。type有以下集中选择：</p>
<p>(1)类型为空白，表示该行是注释，会在处理时被忽略。</p>
<p>(2)类型为data，表示该行包含的是数据。以data开头的行可以出现多次。所有这些行都是该事件的数据。</p>
<p>(3)类型为event，表示该行用来声明事件的类型。浏览器在收到数据时，会产生对应类型的事件。</p>
<p>(4)类型为id，表示该行用来声明事件的标识符。</p>
<p>(5)类型为retry，表示该行用来声明浏览器在连接断开之后进行再次连接之前的等待时间。</p>
<p>比如上面的第一个事件，只传输了一个数据，数据内容为firstevent。服务器端通过这个清单发送到客户端，就可以通过前端进行响应的处理，诸如读取新数据、更新界面等。</p>
<p>客户端需要在JavaScript中使用EventSource对象。</p>
<p>首先需要初始化一个EventSource对象，实例化的时候需要传入与其交互的服务器端的文件地址，如：</p>
<p>vares=newEventSource(“sse.php”);</p>
<p>接下来，可以对进行事件的监听。EventSource给出了三种标准事件，它们的名称和触发时机如下表：</p>
<p>open 当成功与服务器建立连接时执行</p>
<p>message 当收到服务器发送的事件时执行</p>
<p>error 当出现错误时执行</p>
<p>和普通的事件一样，可以通过以下两种方法使用这些事件：</p>
<p>es.onmessage=function(e){};</p>
<p>es.addEventListener(“message”,function(e){});</p>
<h4 id="3、实现"><a href="#3、实现" class="headerlink" title="3、实现"></a>3、实现</h4><p>前端实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;html&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=&quot;UTF-8&quot;&gt;</span><br><span class="line">        &lt;title&gt;basic SSE test&lt;/title&gt;</span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;div id=”content”&gt;&lt;/div&gt;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var es = new EventSource(&quot;sse.php&quot;);</span><br><span class="line">        es.addEventListener(&quot;message&quot;,function(e)&#123;</span><br><span class="line">            document.getElementById(&quot;content&quot;).innerHTML += &quot;\n&quot;+e.data;</span><br><span class="line">        &#125;);</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<p>后端 PHP 实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">header(&apos;Content-Type: text/event-stream&apos;); //这是专门为sse设置的数据格式</span><br><span class="line">$time = date(&apos;Y-m-d H:i:s&apos;);</span><br><span class="line">//下面这些echo出来的东西就是上面说的服务器端和客户端之间的协议</span><br><span class="line">echo &apos;retry: 3000&apos;.PHP_EOL; //retry类型的数据，规定了浏览器在连接断开之后进行再次连接之前的等待时间</span><br><span class="line">echo &apos;data: The server time is: &apos;.$time.PHP_EOL.PHP_EOL;</span><br><span class="line">?&gt;</span><br></pre></td></tr></table></figure>

<h4 id="4、应用"><a href="#4、应用" class="headerlink" title="#### 4、应用"></a>#### 4、应用</h4><p>SSE的优势很明显，它不需要建立或保持大量的客户端发往服务器端的请求，节约了很多资源，提升应用性能。并且SSE的实现非常简单，并且不需要依赖其他插件。</p>
<h3 id="WEBSOCKET"><a href="#WEBSOCKET" class="headerlink" title="WEBSOCKET"></a>WEBSOCKET</h3><p>1、原理<br>WebSocket一种在单个 TCP 连接上进行全双工通讯的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455，并被RFC7936所补充规范。WebSocket API也被W3C定为标准。<br>WebSocket 使得客户端和服务器之间的数据交换变得更加简单，允许服务端主动向客户端推送数据。在 WebSocket API 中，浏览器和服务器只需要完成一次握手，两者之间就直接可以创建持久性的连接，并进行双向数据传输。</p>
<p>它的最大特点就是，服务器可以主动向客户端推送信息，客户端也可以主动向服务器发送信息，是真正的双向平等对话，属于服务器推送技术的一种。</p>
<p>Websocket是应用层第七层上的一个应用层协议，它必须依赖 HTTP 协议进行一次握手 ，握手成功后，数据就直接从 TCP 通道传输，与 HTTP 无关了。</p>
<p>Websocket的数据传输是frame形式传输的，比如会将一条消息分为几个frame，按照先后顺序传输出去。这样做会有几个好处：</p>
<p>1 大数据的传输可以分片传输，不用考虑到数据大小导致的长度标志位不足够的情况。</p>
<p>2 和http的chunk一样，可以边生成数据边传递消息，即提高传输效率。</p>
<p>2、实现<br>客户端实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">var ws = new WebSocket(&quot;wss://echo.websocket.org&quot;);</span><br><span class="line"></span><br><span class="line">ws.onopen = function(evt) &#123; </span><br><span class="line">  console.log(&quot;Connection open ...&quot;); </span><br><span class="line">  ws.send(&quot;Hello WebSockets!&quot;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">ws.onmessage = function(evt) &#123;</span><br><span class="line">  console.log( &quot;Received Message: &quot; + evt.data);</span><br><span class="line">  ws.close();</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">ws.onclose = function(evt) &#123;</span><br><span class="line">  console.log(&quot;Connection closed.&quot;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>说明：<br>WebSocket提供了四个事件操作，如下：</p>
<p>onmessage 收到服务器响应时执行</p>
<p>onerroe 出现异常时执行</p>
<p>onopen 建立起连接时执行</p>
<p>onclose 断开连接时执行</p>
<p>服务端实现<br>WebSocket 服务器的实现，可以查看维基百科的<a href="https://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations" target="_blank" rel="noopener">列表</a>。具体的用法也不一一列举。</p>
<p>3、应用</p>
<p>社交聊天、弹幕、多玩家游戏、协同编辑、股票基金实时报价、体育实况更新、视频会议/聊天、基于位置的应用、在线教育、智能家居等需要高实时的场景。大家感受最深刻的就是微信聊天和 QQ 聊天了。</p>
<h3 id="最后：WebSocket和Socket的区别与联系"><a href="#最后：WebSocket和Socket的区别与联系" class="headerlink" title="最后：WebSocket和Socket的区别与联系"></a>最后：WebSocket和Socket的区别与联系</h3><p>首先，Socket 其实并不是一个协议。它工作在 OSI 模型会话层（第5层），是为了方便大家直接使用更底层协议（一般是 TCP 或 UDP ）而存在的一个抽象层。Socket是对TCP/IP协议的封装，Socket本身并不是协议，而是一个调用接口(API)。</p>
<p>Socket通常也称作”套接字”，用于描述IP地址和端口，是一个通信链的句柄。网络上的两个程序通过一个双向的通讯连接实现数据的交换，这个双向链路的一端称为一个Socket，一个Socket由一个IP地址和一个端口号唯一确定。应用程序通常通过”套接字”向网络发出请求或者应答网络请求。</p>
<p>Socket在通讯过程中，服务端监听某个端口是否有连接请求，客户端向服务端发送连接请求，服务端收到连接请求向客户端发出接收消息，这样一个连接就建立起来了。客户端和服务端也都可以相互发送消息与对方进行通讯，直到双方连接断开</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        
          
        
        <div class="post-tags">
          
            <a href="/tags/web/" rel="tag"># web</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/07/08/聊聊-web-中的网络请求/" rel="next" title="聊聊 web 中的网络请求">
                <i class="fa fa-chevron-left"></i> 聊聊 web 中的网络请求
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/03/mac下使用Vagrant-构建跨平台开发环境/" rel="prev" title="mac 下使用Vagrant 构建跨平台开发环境">
                mac 下使用Vagrant 构建跨平台开发环境 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">启码匠</p>
              <div class="site-description motion-element" itemprop="description">学习如磨刀， 需要不断温故。</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">34</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">47</span>
                    <span class="site-state-item-name">标签</span>
                  
                </div>
              
            </nav>
          

          

          

          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Ajax-轮询"><span class="nav-number">1.</span> <span class="nav-text">Ajax 轮询</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、原理"><span class="nav-number">1.1.</span> <span class="nav-text">1、原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、实现"><span class="nav-number">1.2.</span> <span class="nav-text">2、实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3、应用"><span class="nav-number">1.3.</span> <span class="nav-text">3、应用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#comet"><span class="nav-number">2.</span> <span class="nav-text">comet</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、原理-1"><span class="nav-number">2.1.</span> <span class="nav-text">1、原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、实现-1"><span class="nav-number">2.2.</span> <span class="nav-text">2、实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3、应用-1"><span class="nav-number">2.3.</span> <span class="nav-text">3、应用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SSE"><span class="nav-number">3.</span> <span class="nav-text">SSE</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、概述"><span class="nav-number">3.1.</span> <span class="nav-text">1、概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、原理"><span class="nav-number">3.2.</span> <span class="nav-text">2、原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3、实现"><span class="nav-number">3.3.</span> <span class="nav-text">3、实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4、应用"><span class="nav-number">3.4.</span> <span class="nav-text">#### 4、应用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#WEBSOCKET"><span class="nav-number">4.</span> <span class="nav-text">WEBSOCKET</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最后：WebSocket和Socket的区别与联系"><span class="nav-number">5.</span> <span class="nav-text">最后：WebSocket和Socket的区别与联系</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">启码匠</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> v7.1.2</div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  

  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/schemes/muse.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

  

  

  

  

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":true}});</script></body>
</html>
